import numpy as np
from numpy.random import randint
import cv2 

WIDNOW_NAME = '0'

rectangle = (-1, -1, 0, 0)
bDrawingBox = False

src = np.zeros((600, 800, 3), np.uint8)
tmp = np.zeros((600, 800, 3), np.uint8)

def draw_rectangle(img, box):
    cv2.rectangle(
        img,
        (box[0], box[1]),
        (box[0] + box[2], box[1] + box[3]),
        (randint(0, 256), randint(0, 256), randint(0, 256))
    )

def on_mouse(event, x, y, *args):
    global bDrawingBox, rectangle
    if event == cv2.EVENT_MOUSEMOVE:
        if bDrawingBox:
            rectangle[2] = x - rectangle[0]
            rectangle[3] = y - rectangle[1]
    elif event == cv2.EVENT_LBUTTONDOWN:
        bDrawingBox = True
        rectangle = [x, y, 0, 0]
    elif event == cv2.EVENT_LBUTTONUP:
        bDrawingBox = False
        if rectangle[2] < 0:
            rectangle[0] += rectangle[2]
            rectangle[2] *= -1
        if rectangle[3] < 0:
            rectangle[1] += rectangle[3]
            rectangle[3] *= -1

        draw_rectangle(src, rectangle)


cv2.namedWindow(WIDNOW_NAME)
cv2.setMouseCallback(WIDNOW_NAME, on_mouse)

while True:
    tmp = src.copy()
    if bDrawingBox:
        draw_rectangle(tmp, rectangle)
    cv2.imshow(WIDNOW_NAME, tmp)

    if cv2.waitKey(10) == 27:
        break